import java.sql.SQLOutput;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    public Runnable task;
    public long time;
    public MyTask(Runnable task,long delay) {
        this.task = task;
        this.time = System.currentTimeMillis()+delay;
    }
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    PriorityBlockingQueue<MyTask> priorityBlockingQueue = new PriorityBlockingQueue<>();

    Object key = new Object();

    public void schedule(Runnable runnable,long delay) throws InterruptedException {
        priorityBlockingQueue.put(new MyTask(runnable,delay));
        synchronized(key) {
            key.notify();
        }
    }

    public MyTimer() {
        Thread t = new Thread(() -> {
            while(true) {
                synchronized(key) {
                    try {
                        MyTask myTask = priorityBlockingQueue.take();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTask.time) {
                            myTask.task.run();
                        } else {
                            priorityBlockingQueue.put(myTask);
                            key.wait(myTask.time-curTime);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
}

public class Text {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hehe");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("haha");
            }
        },2000);

        System.out.println("hello");
    }
}
